﻿using DBUtils;
using Dos.ORM;
using LibUtils;
using ModelsUtils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Security.Cryptography;
using System.Web.Http;
using System.Web.UI.WebControls;
using WebApi.Models;
using WebApi.Models.JieShun;
using System.Net.NetworkInformation;

namespace WebApi.Controllers
{
    /// <summary>
    /// 捷顺推送业务接口实现
    /// </summary>
    public class JieShunController : BaseController
    {
        /// <summary>
        /// 接收车辆入场识别记录
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public JieShunResult inrecognition(inrecognitionM inrecognitionM)
        {
            if (ModelState.IsValid)
            {
                DBMain.LogsDebug(inrecognitionM);
                var sql = $@"INSERT INTO inrecognitionM(inRecordId ,  parkId ,  inDeviceId ,  inDeviceName ,  recognitionTime ,  inImage ,  plateNumber ,  plateColor ,  createTime ) VALUES ('{inrecognitionM.inRecordId}', '{inrecognitionM.parkId}',{inrecognitionM.inDeviceId}, '{inrecognitionM.inDeviceName}', '{inrecognitionM.recognitionTime}', '{inrecognitionM.inImage}', '{inrecognitionM.plateNumber}', '{inrecognitionM.plateColor}', '{DateTime.Now}');";
                DbHelperSQL.ExecuteSql(sql);
                return new JieShunResult
                {
                    code = (int)RespCodeEnum.Success,//0:成功，其他为失败，不允许开闸，流程结束
                    msg = "成功！"//code非0时，显示错误信息
                };
            }
            else
            {
                throw new Exceptions("必填字段信息未填写！");
            }

        }

        /// <summary>
        /// 接收车辆出场识别记录
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public JieShunResult outrecognition(outrecognitionM outrecognitionM)
        {
            if (ModelState.IsValid)
            {
                DBMain.LogsDebug(outrecognitionM);
                var sql = $@"INSERT INTO outrecognitionM ( outRecordId ,  parkId ,  outDeviceId ,  outDeviceName ,  recognitionTime ,  inRecordId ,  inDeviceId ,  inDeviceName ,  inTime ,  inImage ,  outImage ,  plateNumber ,  plateColor ,  createTime ) VALUES ('{outrecognitionM.outRecordId}', '{outrecognitionM.parkId}', '{outrecognitionM.outDeviceId}', '{outrecognitionM.outDeviceName}', '{outrecognitionM.recognitionTime}', '{outrecognitionM.inRecordId}', '{outrecognitionM.inDeviceId}', '{outrecognitionM.inDeviceName}', '{outrecognitionM.inTime}', '{outrecognitionM.inImage}', '{outrecognitionM.outImage}', '{outrecognitionM.plateNumber}', '{outrecognitionM.plateColor}', '{DateTime.Now}');";
                DbHelperSQL.ExecuteSql(sql);
                return new JieShunResult
                {
                    code = (int)RespCodeEnum.Success,//0:成功，其他为失败，不允许开闸，流程结束
                    msg = "成功！"//code非0时，显示错误信息
                };
            }
            else
            {
                throw new Exceptions("必填字段信息未填写！");
            }

        }

        /// <summary>
        /// 接收车辆入场记录
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public JieShunResult carin(carinM carinM)
        {
            if (ModelState.IsValid)
            {
                DBMain.LogsDebug(carinM);
                var sql = $@"INSERT INTO carinM(inRecordId,parkId,inDeviceId, inDeviceName, inTime, inImage, plateNumber, plateColor, stationOperator, setmealNo, sealName, parkEventType, remark, createTime) VALUES ('{carinM.inRecordId}', '{carinM.parkId}', '{carinM.inDeviceId}', '{carinM.inDeviceName}', '{carinM.inTime}', '{carinM.inImage}', '{carinM.plateNumber}', '{carinM.plateColor}', '{carinM.stationOperator}', {carinM.setmealNo}, '{carinM.sealName}', '{carinM.parkEventType}', '{carinM.remark}', '{DateTime.Now}');";
                DbHelperSQL.ExecuteSql(sql);
                //if (carinM.plateNumber!="未识别" && carinM.sealName!="月租用户A")
                //{
                //    SetDaPingCarNameStatus(carinM.plateNumber, carinM.inRecordId, carinM.inTime);
                //}
                return new JieShunResult
                {
                    code = (int)RespCodeEnum.Success,//0:成功，其他为失败，不允许开闸，流程结束
                    msg = "成功！"//code非0时，显示错误信息
                };
            }
            else
            {
                throw new Exceptions("必填字段信息未填写！");
            }
        }

        /// <summary>
        /// 接收车辆出场记录
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public JieShunResult carout(caroutM caroutM)
        {
            if (ModelState.IsValid)
            {
                DBMain.LogsDebug(caroutM);
                var sql = $@" INSERT INTO caroutM(parkId, outRecordId, outDeviceId, outDeviceName, inDeviceId, inDeviceName, inRecordId, inTime, outTime, inImage, outImage, plateNumber, plateColor, stationOperator, chargeTotal, discountAmount, charge, setmealNo, sealName, parkEventType, createTime, remark) VALUES('{caroutM.parkId}', '{caroutM.outRecordId}', '{caroutM.outDeviceId}', '{caroutM.outDeviceName}', '{caroutM.inDeviceId}', '{caroutM.inDeviceName}', '{caroutM.inRecordId}', '{caroutM.inTime}', '{caroutM.outTime}', '{caroutM.inImage}', '{caroutM.outImage}', '{caroutM.plateNumber}', '{caroutM.plateColor}', '{caroutM.stationOperator}', {caroutM.chargeTotal}, {caroutM.discountAmount}, {caroutM.charge}, {caroutM.setmealNo}, '{caroutM.sealName}', '{caroutM.parkEventType}', '{DateTime.Now}', '{caroutM.remark}');";

                DbHelperSQL.ExecuteSql(sql);
                //if (caroutM.plateNumber != "未识别" && caroutM.sealName != "月租用户A")
                //{
                //    UpDaPingCarNameStatus(caroutM.plateNumber, caroutM.inRecordId, caroutM.outTime);
                //}
                return new JieShunResult
                {
                    code = (int)RespCodeEnum.Success,//0:成功，其他为失败，不允许开闸，流程结束
                    msg = "成功！"//code非0时，显示错误信息
                };
            }
            else
            {
                throw new Exceptions("必填字段信息未填写！");
            }

        }

        #region 获取车辆状态  暂时不做处理
        /// <summary>
        /// 根据入场记录，写入中间表
        /// </summary>
        /// <param name="FCarName"></param>
        /// <param name="FInRecordId"></param>
        /// <param name="FInTime"></param>
        private void SetDaPingCarNameStatus(string FCarName, string FInRecordId,string FInTime)
        {
            var sql = $@"SELECT b.FQty, b.FCommitQty, b.FAuxStockQty, a.FDate, a.FInterID, a.FBillNo, a.FHeadSelfS0238, c.FItemID, c.FName from JinHai.AIS20151130222535.dbo.SEOutStock AS a
INNER JOIN JinHai.AIS20151130222535.dbo.SEOutStockEntry AS b ON a.FInterID= b.FInterID
INNER JOIN JinHai.AIS20151130222535.dbo.t_ICItem AS c ON b.FItemID= c.FItemID
WHERE  (a.FStatus = 1 or a.FStatus = 2) AND a.FClosed  = 0 AND
a.FHeadSelfS0238 LIKE '%{FCarName}'";
            var dt = DbHelperSQL.Query(sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                var FBillNo=string.Empty;
                var FWuliaoName = string.Empty;
                foreach (DataRow item in dt.Rows)
                {
                    FBillNo += item["FBillNo"].ToString()+"，";
                    FWuliaoName += item["FName"].ToString() + "，"; 
                }
                //车辆状态：1 已入场 2 装货中 3 装货完成 4 已出场
                var insertsql = $@"INSERT INTO CarStatus (FInRecordId, FBillNo, FCarName, FWuliaoName, FInTime, FCreatTime, FStatus) VALUES('{FInRecordId}', '{FBillNo}', '{FCarName}', '{FWuliaoName}', '{FInTime}', '{DateTime.Now}', '已入场');";
                DbHelperSQL.ExecuteSql(insertsql);

                //var insertsql = $@"INSERT INTO CarStatus (FInRecordId, FBillNo, FCarName, FWuliaoName, FInTime, FOutTime, FTareTime, FTotalTime, FCreatTime, FUpdateTime, FStatus) VALUES('{FInRecordId}', '{FBillNo}', '{FCarName}', '{FWuliaoName}', '{FInTime}', '{FOutTime}', '{FTareTime}', '{FTotalTime}', '{DateTime.Now}', '{FUpdateTime}',1);";
            }
            else
            {
                var insertsql = $@"INSERT INTO CarStatus (FInRecordId, FCarName, FInTime, FCreatTime, FStatus) VALUES('{FInRecordId}', '{FCarName}',  '{FInTime}', '{DateTime.Now}', '已入场');";
                DbHelperSQL.ExecuteSql(insertsql);
            }
        }
        /// <summary>
        /// 根据出场记录，更新中间表
        /// </summary>
        /// <param name="FCarName"></param>
        /// <param name="FInRecordId"></param>
        /// <param name="FInTime"></param>
        private void UpDaPingCarNameStatus(string FCarName, string FInRecordId, string FOutTime)
        {
            var updatesql = $@"UPDATE CarStatus SET FOutTime='{FOutTime}', FStatus='已出场' WHERE FInRecordId='{FInRecordId}' AND FCarName='{FCarName}';";
            DbHelperSQL.ExecuteSql(updatesql);
        }
        #endregion
    }
}